#! -*- coding: utf-8 -*-
"""
"""
import math

import requests, json
import datetime
import time,os
import base64,hashlib
class chat_qywx:
    def __init__(self,key):
        self.qywx_url  = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key="+key
        self.qywx_upload_url="https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?debug=1&key="+key+"&type=file"
        self.send_message=""
    def set_every_send_message(self,msg):
        self.send_message = msg
    def get_current_time(self):
        """获取当前时间，当前时分秒"""
        now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        hour = datetime.datetime.now().strftime("%H")
        mm = datetime.datetime.now().strftime("%M")
        ss = datetime.datetime.now().strftime("%S")
        return now_time, hour, mm, ss


    def sleep_time(self,hour, m, sec):
        """返回总共秒数"""
        return hour * 3600 + m * 60 + sec

    def split_msg(self,msg,size=4096):
        s=[]
        n0=len(msg)
        b=msg.encode("utf-8")
        n1=len(b)
        if n1>size:
            m=int(n1/size)+1
            n1=0
            size=n0/m
            for i in range(1,m):
                n2=int(size*i)
                while msg[n2]!="\n":
                    n2=n2+1
                if msg[n2]=="\n":
                    s.append(msg[n1:n2])
                    n1=n2+1
            s.append(msg[n1:])
        else:
            s.append(msg)
        return s
    def send_msg(self,msg,at_name_list=[],at_phone_list=[]):
        """艾特全部，并发送指定信息"""
        msgs=self.split_msg(msg)
        for msg in msgs:
            data = json.dumps({"msgtype": "text", "text": {"content": msg, "mentioned_list":at_name_list,"mentioned_mobile_list":at_phone_list}})
            r = requests.post(self.qywx_url, data, auth=('Content-Type', 'application/json'))
            print(r.json())
        return r.json()
    def send_markdown(self,markdown):
        data = json.dumps({"msgtype": "markdown", "markdown": {"content": markdown}})
        r = requests.post(self.qywx_url, data, auth=('Content-Type', 'application/json'))
        print(r.json())
        return r.json()
    def send_image(self,image_url):
        with open(image_url,"rb") as f:
            s=f.read()
            base64_data=base64.b64encode(s)
            data_base64=base64_data.decode()
            md=hashlib.md5()
            md.update(s)
            data_md5=md.hexdigest()
            data = json.dumps({"msgtype": "image", "image": {"base64": data_base64,
            "md5": data_md5}})
            r = requests.post(self.qywx_url, data, auth=('Content-Type', 'application/json'))
            print(r.json())
            return r.json()
    def send_news(self,title,description,url,picurl):
        data = json.dumps({"msgtype": "news", "news": {"articles": [{
               "title" : title,
               "description" : description,
               "url" : url,
               "picurl" : picurl
           }]}})
        r = requests.post(self.qywx_url, data, auth=('Content-Type', 'application/json'))
        print(r.json())
        return r.json()
    def upload_file(self,file_url):
        url=os.path.abspath(file_url)
        name=url.split(os.path.sep)[-1]
        # type0=url.split(".")[-1]
        with open(file_url,"rb") as f:
            data={name:f.read()}
            r = requests.post(self.qywx_upload_url, files=data)
            print(r.json())
            # m = MultipartEncoder(
            #     fields={name: ('file', f, 'text/plain')},
            # )
            # r = requests.post(url=url, data=m, headers={'Content-Type': m.content_type})
            return r.json()
    def send_file(self,file_url):
        id=self.upload_file(file_url)
        if id is not None:
            data = json.dumps({
                "msgtype": "file",
                "file": {
                     "media_id": id["media_id"]
                }
            })
            r = requests.post(self.qywx_url, data, auth=('Content-Type', 'application/json'))
            print(r.json())
            return r.json()

    def every_time_send_msg(self,interval_h=0, interval_m=1, interval_s=0, special_h="00", special_m="00", mode="special"):
        """每天指定时间发送指定消息"""

        # 设置自动执行间隔时间
        second = self.sleep_time(interval_h, interval_m, interval_s)
        # 死循环
        while 1 == 1:
            # 获取当前时间和当前时分秒
            c_now, c_h, c_m, c_s = self.get_current_time()
            print("当前时间：", c_now, c_h, c_m, c_s)
            if mode == "special":
                if c_h == special_h and c_m == special_m:
                    # 执行
                    print("正在发送...")
                    self.send_msg(self.send_message)
            else:
                self.send_msg(self.send_message)
            print("每隔" + str(interval_h) + "小时" + str(interval_m) + "分" + str(interval_s) + "秒执行一次")
            # 延时
            time.sleep(second)


if __name__ == '__main__':
    #every_time_send_msg(mode="no")
    key = "14570918-3143-4cab-92b2-ba8a9ae6e8f7"
    chat=chat_qywx(key)
    # chat.send_msg("我只测试下,lallala",at_phone_list=["13902101481"])
    # chat.send_image(r"F:\ss\F_merge\figure\产品.png")
    chat.send_file(r"F:\ss\F_merge\figure\产品产品.png")
